package player

import (
	"GameServer/Common/utils"

	log "github.com/sirupsen/logrus"

	"GameServer/Common/data"
	"GameServer/Game/advert"
	"GameServer/Game/errors"
	"GameServer/Game/lib"
	"GameServer/Game/m"
	"GameServer/Game/plog"
	"GameServer/Game/sp"
)

func (p *Player) OpenGridRequest(req *sp.OpenGridRequest) (res *sp.OpenGridResponse, err error) {

	// mGrids, isFireGrid, openAltar, uProp, openGridNum, storyStatus, err := lib.OpenGrid(req.GridId, p.User, false)
	// if err != nil {
	// 	res = &sp.OpenGridResponse{
	// 		Errcode: errors.ErrCode(err),
	// 	}
	// 	return res, err
	// }
	// // 是烧焦的格子 而且 是第一次打开
	// if isFireGrid && !p.User.IsOpenFireGrid() {
	// 	p.User.OpenFireGrid()
	// 	// p.User.RemoveFireProtec()
	// 	// slot.RemoveFireProtec(p.User.Uid.Hex())
	// }
	// // 有委托完成
	// if num := lib.EntrustCheck(p.User); num > 0 {
	// 	utils.AsyncFunc(func() {
	// 		p.Send(&sp.EntrustNoticeRequest{
	// 			Num: num,
	// 		})
	// 	})
	// }

	// p.TimelyUpdateProp(req.GetType(), uProp)
	// utils.AsyncFunc(func() {
	// 	p.UpdateProp(req.GetType(), uProp)
	// })

	// if p.User.UnionId != "" && openAltar {
	// 	uProp1, _, _, err := lib.GiveGoodsByKv("OpenGridRequest", p.User, m.BaseKV{Key: data.GlobalEnum.Union, Val: 1}, p.Send)
	// 	if err != nil {
	// 		log.WithFields(log.Fields{
	// 			"data":   m.BaseKV{Key: data.GlobalEnum.Union, Val: 1},
	// 			"uid":    p.User.Uid.Hex(),
	// 			"method": "OpenGridRequest",
	// 		}).Error("给公会积分失败")
	// 	} else {
	// 		p.TimelyUpdateProp(req.GetType(), uProp1)
	// 		utils.AsyncFunc(func() {
	// 			p.UpdateProp(req.GetType(), uProp1)
	// 		})
	// 	}
	// }
	// // 有成就完成，进行通知
	// achLst := lib.AchievComplete(p.User)
	// if len(achLst) > 0 {
	// 	p.Send(&sp.AchievementNoticeRequest{
	// 		Lst: achLst,
	// 	})
	// }

	// res = &sp.OpenGridResponse{
	// 	GridList:    lib.FormartGridInfoSps(mGrids),
	// 	GridId:      req.GridId,
	// 	OpenGridNum: openGridNum,
	// 	StoryStatus: storyStatus,
	// }
	return
}

func (p *Player) OpenGridListRequest(req *sp.OpenGridListRequest) (res *sp.OpenGridListResponse, err error) {
	us := p.User
	grids := make(map[int64]*m.GridInfo, 0)
	var gridsNeedToOpen = req.GridIdList
	var openGridNumResponse int64
	var storyStatusResponse int64
	var openAltarResponse int64
	var gridsOpen []int64
	for _, gridId := range gridsNeedToOpen { //逐个开格子
		mGrids, _, openAltar, uProp, openGridNum, storyStatus, lockBrick, err := lib.OpenGrid(gridId, p.User, false, false)
		if lockBrick {
			continue
		}
		if err != nil {
			res = &sp.OpenGridListResponse{
				GridList:    lib.FormartGridInfoSps(grids),
				GridIdList:  gridsOpen,
				OpenGridNum: openGridNumResponse,
				StoryStatus: storyStatusResponse,
				OpenAltar:   openAltarResponse,
				Errcode:     errors.ErrCode(err),
			}
			return res, err
		}

		gridsOpen = append(gridsOpen, gridId)
		openGridNumResponse = openGridNum
		if storyStatus != 0 {
			storyStatusResponse = storyStatus
		}
		p.TimelyUpdateProp(req.GetType(), uProp)
		utils.AsyncFunc(func() {
			p.UpdateProp(req.GetType(), uProp)
		})

		if openAltar {
			openAltarResponse = 1
			// 成就，记录开启祭坛数量。
			lib.AddAchievProgress(p.User, data.AchievementType.Pick_alter, 1)
		}
		if p.User.UnionId != "" && openAltar {
			uProp1, _, _, err := lib.GiveGoodsByKv("OpenGridRequest", p.User, m.BaseKV{Key: data.GlobalEnum.Union, Val: 1}, p.Send)
			if err != nil {
				log.WithFields(log.Fields{
					"data":   m.BaseKV{Key: data.GlobalEnum.Union, Val: 1},
					"uid":    p.User.Uid.Hex(),
					"method": "OpenGridRequest",
				}).Error("给公会积分失败")
			} else {
				p.TimelyUpdateProp(req.GetType(), uProp1)
				utils.AsyncFunc(func() {
					p.UpdateProp(req.GetType(), uProp1)
				})
			}
		}

		for _, grid := range mGrids {
			grids[grid.Id] = grid
		}
		// 统计挖砖块的成就
		lib.AddAchievProgress(us, data.AchievementType.Treasure, int64(len(mGrids)))
	}
	// 有委托完成
	if num := lib.EntrustCheck(us); num > 0 {
		utils.AsyncFunc(func() {
			p.Send(&sp.EntrustNoticeRequest{
				Num: num,
			})
		})
	}
	// 有成就完成，进行通知
	achLst := lib.AchievComplete(us)
	if len(achLst) > 0 {
		p.Send(&sp.AchievementNoticeRequest{
			Lst: achLst,
		})
	}

	if lib.NewGuideRecomUnion(us, int64(len(grids))) {
		//给玩家推荐公会
		p.RecomUnion()
	}

	grids, _ = lib.MonsterLockBrick(us, grids)

	res = &sp.OpenGridListResponse{
		GridList:    lib.FormartGridInfoSps(grids),
		GridIdList:  gridsOpen,
		OpenGridNum: openGridNumResponse,
		StoryStatus: storyStatusResponse,
		OpenAltar:   openAltarResponse,
	}
	return
}

func (p *Player) UseGridGoodsRequest(req *sp.UseGridGoodsRequest) (res *sp.UseGridGoodsResponse, err error) {
	us := p.User

	goodsTid, grids, uProp, resGoods, boxResList, err := lib.UseGridGoods(req.GridId, us, p.Send)
	if err != nil {
		res = &sp.UseGridGoodsResponse{
			Errcode: errors.ErrCode(err),
		}
		return res, err
	}

	if goodsTid == 150410 { // 电视机
		advert.Module.AddAdCnt(data.AdTV)                         // 统计金币广告
		advert.Module.AddAdUser(us.Uid.Hex(), us.Name, data.AdTV) // 统计金币广告
	}

	// 有成就完成，进行通知
	achLst := lib.AchievComplete(us)
	if len(achLst) > 0 {
		p.Send(&sp.AchievementNoticeRequest{
			Lst: achLst,
		})
	}

	plog.Log_WaBaoLog(us, goodsTid, resGoods, uProp)
	p.TimelyUpdateProp(req.GetType(), uProp)
	utils.AsyncFunc(func() {
		p.UpdateProp(req.GetType(), uProp)
	})

	res = &sp.UseGridGoodsResponse{
		GridList: lib.FormartGridInfoSps(grids),
		GridId:   req.GridId,
		Res:      lib.FormatGoodsInfoSps(resGoods),
		GoodsTid: goodsTid,
		BoxRes:   lib.FormatBoxResSps(boxResList),
	}
	return
}

func (p *Player) MoveLayerRequest(req *sp.MoveLayerRequest) (res *sp.MoveLayerResponse, err error) {

	switch req.Op {
	//刷新当前层
	case 1:
		layer, err := lib.RefreshLayer(p.User)
		if err != nil {
			res = &sp.MoveLayerResponse{
				Errcode: errors.ErrCode(err),
			}
			return res, err
		}
		res = &sp.MoveLayerResponse{
			Layer: lib.FormartLayerSp(layer),
		}
		return res, nil
	// 上一层
	case 2:
		layer, err := lib.PreLayer(p.User)
		if err != nil {
			res = &sp.MoveLayerResponse{
				Errcode: errors.ErrCode(err),
			}
			return res, err
		}
		res = &sp.MoveLayerResponse{
			Layer: lib.FormartLayerSp(layer),
		}
		return res, nil
	// 下一层
	case 3:
		layer, err := lib.NextLayer(p.User)
		if err != nil {
			res = &sp.MoveLayerResponse{
				Errcode: errors.ErrCode(err),
			}
			return res, err
		}
		res = &sp.MoveLayerResponse{
			Layer: lib.FormartLayerSp(layer),
		}
		return res, nil

	case 4: // 到达任意层
		layer, err := lib.MoveLayer(p.User, req.Id)
		if err != nil {
			res = &sp.MoveLayerResponse{
				Errcode: errors.ErrCode(err),
			}
			return res, err
		}
		res = &sp.MoveLayerResponse{
			Layer: lib.FormartLayerSp(layer),
		}
		return res, nil

	default:
		log.WithFields(log.Fields{
			"uid":    p.User.Uid.Hex(),
			"method": "MoveLayerRequest",
			"data":   req,
		}).Error("无效的操作op")
	}
	return
}

func (p *Player) MoveLockBlockRequest(req *sp.MoveLockBlockRequest) (res *sp.MoveLockBlockResponse, err error) {
	us := p.User
	switch req.Op {
	case 1: // 放弃关卡
		lockBlock, uProp, err := lib.RefreshCurrentLockBlock(us)
		if err != nil {
			res = &sp.MoveLockBlockResponse{
				Errcode: errors.ErrCode(err),
			}
			return res, err
		}
		if uProp != nil {
			p.TimelyUpdateProp(req.GetType(), uProp)
			utils.AsyncFunc(func() {
				p.UpdateProp(req.GetType(), uProp)
			})
		}
		res = &sp.MoveLockBlockResponse{
			LockBlocks: lib.FormartLockBlockSp(lockBlock),
			Pos:        lib.FormatUserPosInfoSp(us.Pos),
		}
	case 2: // 上一关
		lockBlock, err := lib.PreLockBlock(us)
		if err != nil {
			res = &sp.MoveLockBlockResponse{
				Errcode: errors.ErrCode(err),
			}
			return res, err
		}
		res = &sp.MoveLockBlockResponse{
			LockBlocks: lib.FormartLockBlockSp(lockBlock),
			Pos:        lib.FormatUserPosInfoSp(us.Pos),
		}
		utils.AsyncFunc(func() {
			p.RefreshSlotUser()
		})
	case 3: // 下一关
		// 成就，记录关卡打开全部格子
		lib.AchievOpenAllGrids(us)
		// 成就，记录未开格子数，通关
		lib.AchievSurplusAllGrids(us)

		lockBlock, err := lib.NextLockBlock(us)
		// 有成就完成，进行通知
		achLst := lib.AchievComplete(us)
		if len(achLst) > 0 {
			p.Send(&sp.AchievementNoticeRequest{
				Lst: achLst,
			})
		}

		// 计算新兵特训
		lib.RecruitTrainMsg(us.Uid.Hex(), us.MaxPos.LockBlockTid, 0, 0, p.Send)
		if err != nil {
			res = &sp.MoveLockBlockResponse{
				Errcode: errors.ErrCode(err),
			}
			return res, err
		}
		res = &sp.MoveLockBlockResponse{
			LockBlocks: lib.FormartLockBlockSp(lockBlock),
			Pos:        lib.FormatUserPosInfoSp(us.Pos),
		}
		utils.AsyncFunc(func() {
			p.RefreshSlotUser()
		})
		if lib.NewGuidePushActive(us) {
			p.PushAllActActivityInfo()
		}
	case 4: // 到达任意关卡
		lockBlock, err := lib.MoveLockBlock(us, req.Id)
		if err != nil {
			res = &sp.MoveLockBlockResponse{
				Errcode: errors.ErrCode(err),
			}
			return res, err
		}
		res = &sp.MoveLockBlockResponse{
			LockBlocks: lib.FormartLockBlockSp(lockBlock),
			Pos:        lib.FormatUserPosInfoSp(us.Pos),
		}

	default:
		log.WithFields(log.Fields{
			"uid":    us.Uid.Hex(),
			"method": "MoveLockBlockRequest",
			"data":   req,
		}).Debug("无效的操作op")
	}
	return
}

func (p *Player) LockBlockRewardRequest(req *sp.LockBlockRewardRequest) (res *sp.LockBlockRewardResponse, err error) {
	uProp, resGoods, boxRes, err := lib.LockBlockReward("LockBlockRewardRequest", p.User, req.Id, p.Send)
	if err != nil {
		res = &sp.LockBlockRewardResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}
	// 有成就完成，进行通知
	achLst := lib.AchievComplete(p.User)
	if len(achLst) > 0 {
		p.Send(&sp.AchievementNoticeRequest{
			Lst: achLst,
		})
	}
	res = &sp.LockBlockRewardResponse{
		Rewards: lib.FormatGoodsInfoSps(resGoods),
		Id:      req.Id,
		Status:  2,
		BoxRes:  lib.FormatBoxResSps(boxRes),
	}
	p.TimelyUpdateProp(req.GetType(), uProp)
	utils.AsyncFunc(func() {
		p.UpdateProp(req.GetType(), uProp)
	})
	return
}

func (p *Player) AltarStatusRequest(req *sp.AltarStatusRequest) (res *sp.AltarStatusResponse) {
	layer := p.User.GetLayer()
	altar, ok := lib.GetLayerAltarByGridId(layer.Altars, req.Gid)
	if !ok {
		res = &sp.AltarStatusResponse{
			Errcode: data.Errcode.ServerErr,
		}
		return
	}
	res = &sp.AltarStatusResponse{
		Status: altar.Status,
	}
	return
}

func (p *Player) AltarRewardRequest(req *sp.AltarRewardRequest) (res *sp.AltarRewardResponse, err error) {
	uProp, op, roll, resGoods, err := lib.GetAltarRewards("AltarRewardRequest", p.User, req.Gid, p.Send)
	if err != nil {
		res = &sp.AltarRewardResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}
	// 有成就完成，进行通知
	achLst := lib.AchievComplete(p.User)
	if len(achLst) > 0 {
		p.Send(&sp.AchievementNoticeRequest{
			Lst: achLst,
		})
	}
	res = &sp.AltarRewardResponse{
		Op:      op,
		Roll:    roll,
		Rewards: lib.FormatGoodsInfoSps(resGoods),
	}
	if uProp != nil {
		p.TimelyUpdateProp(req.GetType(), uProp)
		utils.AsyncFunc(func() {
			p.UpdateProp(req.GetType(), uProp)
		})
	}
	return
}
